<template>
  <!-- 初始化添加页面 -->
  <div
    v-loading="btnDisabled"
    element-loading-text="正在为您修改,请等待"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    :title="initTitle"
    :visible="initVisible"
    :before-close="cancel"
  >
    <div style="text-align:left;">
      <el-form
        ref="initEnterpriseForm"
        :model="initEnterprise"
        :rules="initRules"
        label-width="80px"
      >
        <el-row>
          <el-col :lg="{span:16,offset: 4}" :xl="{span:12,offset: 6}" align="center">
            <div class="grid-content bg-purple">企业信息</div>
          </el-col>
          <el-col :xs="15" :sm="12" :md="10" :lg="{span:8,offset: 4}" :xl="{span:6,offset: 6}">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="initEnterprise.enterpriseName" size="medium" :disabled="true" @input="handleInput" />
            </el-form-item>
          </el-col>
          <el-col :xs="15" :sm="12" :md="10" :lg="8" :xl="6">
            <el-form-item label="到期时间" prop="enterpriseExpiryTime">
              <el-date-picker
                v-model="initEnterprise.enterpriseExpiryTime"
                type="date"
                :picker-options="expireTimeOption"
                style="width:100%"
                placeholder="选择到期时间"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="{span:16,offset: 4}" :xl="{span:12,offset: 6}" align="center">
            <div class="grid-content bg-purple">部门编码信息</div>
          </el-col>
          <el-col :xs="15" :sm="12" :md="10" :lg="{span:8,offset: 4}" :xl="{span:6,offset: 6}">
            <el-form-item label="英文名称" prop="encodeEnName">
              <el-input v-model="initEnterprise.encodeEnName" size="medium" />
            </el-form-item>
          </el-col>
          <el-col :xs="15" :sm="12" :md="10" :lg="8" :xl="6">
            <el-form-item label="编码名称" prop="caption">
              <el-input v-model="initEnterprise.caption" size="medium" />
            </el-form-item>
          </el-col>
          <el-col :xs="15" :sm="12" :md="10" :lg="{span:8,offset: 4}" :xl="{span:6,offset: 6}">
            <el-form-item label="编码规则" prop="ruleValue">
              <el-input v-model.number="initEnterprise.ruleValue" size="medium" @change="changRuleLength">
                <template slot="prepend">1</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="15" :sm="12" :md="10" :lg="8" :xl="6">
            <el-form-item label="规则长度" prop="ruleLength">
              <el-input v-model="initEnterprise.ruleLength" size="medium" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :lg="{span:16,offset: 4}" :xl="{span:12,offset: 6}" align="center">
            <div class="grid-content bg-purple">部门管理员角色</div>
          </el-col>
          <el-col :xs="15" :sm="12" :md="10" :lg="{span:8,offset: 4}" :xl="{span:6,offset: 6}">
            <el-form-item label="角色名称" prop="deptRoleName">
              <el-input v-model="initEnterprise.deptRoleName" size="medium" />
            </el-form-item>
          </el-col>
          <el-col :xs="15" :sm="12" :md="10" :lg="8" :xl="6">
            <el-form-item label="权限字符" prop="deptRoleKey">
              <el-input v-model="initEnterprise.deptRoleKey" size="medium" />
            </el-form-item>
          </el-col>
          <el-col :lg="{span:16,offset: 4}" :xl="{span:12,offset: 6}" align="center">
            <div class="grid-content bg-purple">企业管理员角色</div>
          </el-col>
          <el-col :xs="15" :sm="12" :md="10" :lg="{span:8,offset: 4}" :xl="{span:6,offset: 6}">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="initEnterprise.roleName" size="medium" />
            </el-form-item>
          </el-col>
          <el-col :xs="15" :sm="12" :md="10" :lg="8" :xl="6">
            <el-form-item label="权限字符" prop="roleKey">
              <el-input v-model="initEnterprise.roleKey" size="medium" />
            </el-form-item>
          </el-col>
          <el-col :lg="{span:16,offset: 4}" :xl="{span:12,offset: 6}" align="center">
            <div class="grid-content bg-purple">管理员信息</div>
          </el-col>
          <el-col :xs="15" :sm="12" :md="10" :lg="{span:8,offset: 4}" :xl="{span:6,offset: 6}">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="initEnterprise.userName" size="medium" />
            </el-form-item>
          </el-col>
          <el-col :xs="15" :sm="12" :md="10" :lg="8" :xl="6">
            <el-form-item label="登录账号" prop="loginName">
              <el-input v-model="initEnterprise.loginName" auto-complete="off" size="medium" />
            </el-form-item>
          </el-col>
          <el-col :xs="15" :sm="12" :md="10" :lg="{span:8,offset: 4}" :xl="{span:6,offset: 6}">
            <el-form-item label="登录密码" prop="password">
              <el-input v-model="initEnterprise.password" type="password" autocomplete="new-password" size="medium" />
            </el-form-item>
          </el-col>
          <el-col :xs="15" :sm="12" :md="10" :lg="8" :xl="6">
            <el-form-item label="确认密码" prop="Confirmpassword">
              <el-input v-model="initEnterprise.Confirmpassword" size="medium" type="password" />
            </el-form-item>
          </el-col>
          <el-col :lg="{span:16,offset: 4}" :xl="{span:12,offset: 6}">
            <el-form-item label="套餐选择" prop="tempId">
              <el-select v-model="initEnterprise.tempId" style="width:100%" @change="selectTrigger">
                <el-option
                  v-for="item in templateOptiom"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="{span:16,offset: 4}" :xl="{span:12,offset: 6}" align="center">
            <div class="grid-content bg-purple">数据权限</div>
          </el-col>
          <el-col :lg="{span:16,offset: 4}" :xl="{span:12,offset: 6}">
            <el-form label-width="110px">
              <el-form-item label="菜单权限" class="el-tree-wrap">
                <p class="all-expand">
                  <span v-if="AddExpand" @click="unFoldAll()"><i class="el-icon-caret-bottom" />全部展开</span>
                  <span v-else @click="closeAll()"><i class="el-icon-caret-top" />全部关闭</span>
                </p>
                <div class="el-tree-cont">
                  <el-tree
                    ref="menu"
                    :data="menuOptions"
                    show-checkbox
                    node-key="id"
                    empty-text="加载中，请稍后"
                    :props="defaultProps"
                  />
                </div>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="medium" @click="cancel">取 消</el-button>
      <el-button size="medium" type="primary" :disabled="btnDisabled" @click="submitForm">保 存</el-button>
    </span>
  </div>
</template>

<script>
import { initAdd, listSysCompanyTemp } from '@/api/enterprise/audit'
import { selectSysCompanyTempMenuIdsById } from '@/api/enterprise/everday'
import { checkLoginNameUnique } from '@/api/system/user'
import { checkRoleKeyUnique } from '@/api/system/role'
// 菜单树
import { selectTreeMenu } from '@/api/system/menu'
export default {
  name: 'Init',
  data() {
    // form表单自定义查重验证
    const validLoginName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('登录账号不能为空'))
      } else {
        const userId = ''
        const loginName = value
        checkLoginNameUnique(userId, loginName).then(res => {
          if (res.data === '1') {
            return callback(new Error('登录账号已经存在'))
          } else {
            callback()
          }
        })
      }
    }
    const loginNameLength = (rule, value, callback) => {
      if (value.length < 2 || value.length > 20) {
        return callback(new Error('登录账号不能少于2位且不能大于20位'))
      } else {
        callback()
      }
    }
    const passwordLength = (rule, value, callback) => {
      if (value.length < 6 || value.length > 20) {
        return callback(new Error('登录密码不能少于6位且不能大于20位'))
      } else {
        callback()
      }
    }
    const passwordAlike = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('确认密码不能为空'))
      } else if (this.initEnterprise.password !== value) {
        return callback(new Error('确认密码与登录密码不一致'))
      } else {
        callback()
      }
    }
    // 权限字符查询数据库重复
    const checkRoleKey = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('权限字符不能为空'))
      } else {
        const roleId = ''
        const roleKey = value
        checkRoleKeyUnique(roleId, roleKey).then(res => {
          console.log(res)
          if (res.data === '1') {
            return callback(new Error('权限字符已经存在'))
          } else {
            callback()
          }
        })
      }
    }
    // 权限字符查询重复
    const checkDeptRoleKey = (rule, value, callback) => {
      if (value === this.initEnterprise.roleKey) {
        return callback(new Error('权限字符已经存在'))
      } else {
        callback()
      }
    }
    // 权限字符查询重复
    const checkroleKey = (rule, value, callback) => {
      if (value === this.initEnterprise.deptRoleKey) {
        return callback(new Error('权限字符已经存在'))
      } else {
        callback()
      }
    }
    const checkroleName = (rule, value, callback) => {
      if (value === this.initEnterprise.deptRoleName) {
        return callback(new Error('角色名称已经存在'))
      } else {
        callback()
      }
    }
    const checkDeptroleName = (rule, value, callback) => {
      if (value === this.initEnterprise.roleName) {
        return callback(new Error('角色名称已经存在'))
      } else {
        callback()
      }
    }
    return {
      // 模板名称
      templateOptiom: [],
      // 初始化内容标题
      initTitle: '',
      beforeRuleValue: '1',
      initVisible: false,
      // 初始化from表单
      initEnterprise: {
        // 企业id
        enterpriseId: '',
        // 分公司id
        subCompany: '',
        // 企业名称
        enterpriseName: '',
        // 英文名称
        encodeEnName: '',
        // 名称
        caption: '',
        // 规则
        ruleValue: '',
        // 长度
        ruleLength: '',
        // 部门管理员名称
        deptRoleName: '',
        // 权限字符
        deptRoleKey: '',
        // 角色名称
        roleName: '',
        roleKey: '',
        userName: '',
        loginName: '',
        password: '',
        Confirmpassword: '',
        // 企业到期时间
        enterpriseExpiryTime: '',
        tempId: '',
        menuIds: []
      },
      expireTimeOption: {
        disabledDate(date) {
          return date.getTime() <= Date.now()
        }
      },
      AddExpand: true,
      btnDisabled: false,
      initRules: {
        encodeEnName: [
          { required: true, message: '英文名称不能为空', trigger: 'blur' }
        ],
        caption: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        ruleValue: [
          { required: true, message: '规则不能为空', trigger: 'blur' },
          { type: 'number', required: true, message: '规则必须为数值', trigger: 'blur' }
        ],
        ruleLength: [
          { required: true, message: '长度不能为空', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' }
        ],
        loginName: [
          { required: true, message: '登录账号不能为空', trigger: 'blur' },
          // 自定义验证方式
          { required: true, validator: validLoginName, trigger: 'blur' },
          { required: true, validator: loginNameLength, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '登录密码不能为空', trigger: 'blur' },
          { required: true, validator: passwordLength, trigger: 'blur' }
        ],
        Confirmpassword: [
          { required: true, validator: passwordAlike, trigger: 'blur' }
        ],
        enterpriseExpiryTime: [
          { required: true, message: '企业到期时间不能为空', trigger: 'blur' }
        ],
        tempId: [
          { required: true, message: '企业套餐不能为空', trigger: 'blur' }
        ],
        deptRoleName: [
          { required: true, message: '必填', trigger: 'blur' },
          { required: true, validator: checkDeptroleName, trigger: 'blur' }
        ],
        deptRoleKey: [
          { required: true, message: '必填', trigger: 'blur' },
          { required: true, validator: checkRoleKey, trigger: 'blur' },
          { required: true, validator: checkDeptRoleKey, trigger: 'blur' }
        ],
        roleName: [
          { required: true, message: '必填', trigger: 'blur' },
          { required: true, validator: checkroleName, trigger: 'blur' }
        ],
        roleKey: [
          { required: true, message: '必填', trigger: 'blur' },
          { required: true, validator: checkRoleKey, trigger: 'blur' },
          { required: true, validator: checkroleKey, trigger: 'blur' }
        ]
      },
      // 树形菜单数据
      menuOptions: [],
      // 加载树形菜单结构
      defaultProps: {
        children: 'children',
        label: 'label',
        disabled: this.disabledFn
      }
    }
  },
  created() {
    this.templateDataList()
  },
  methods: {
    // 自动生成角色和权限标识
    handleInput(val) {
      const pinyin = require('pinyin')
      let a = pinyin(val, {
        style: pinyin.STYLE_FIRST_LETTER
      })
      a = a.join('')
      // 转大写
      a = a.toUpperCase()
      console.log(a.toUpperCase(), 222) // ['g']
      this.initEnterprise.deptRoleName = val + '部门管理员'
      this.initEnterprise.deptRoleKey = a + '_DEPT'
      this.initEnterprise.roleName = val + '企业管理员'
      this.initEnterprise.roleKey = a + '_SYSTEM'
    },
    // 全部展开
    unFoldAll() {
      this.AddExpand = false
      const nodes = this.$refs.menu.store.nodesMap
      for (const i in nodes) {
        nodes[i].expanded = true
      }
    },
    // 全部关闭
    closeAll() {
      this.AddExpand = true
      const nodes = this.$refs.menu.store.nodesMap
      for (const i in nodes) {
        nodes[i].expanded = false
      }
    },
    // 初始化添加页面
    addFrom(id, name) {
      this.empetyInitEnterprise()
      this.getMenuTreeData()
      this.initEnterprise.enterpriseId = id
      this.initEnterprise.subCompany = id
      this.initEnterprise.enterpriseName = name
      this.handleInput(name)
      this.initTitle = '初始化企业'
      this.initVisible = true
    },
    // 清空初始化表单
    empetyInitEnterprise() {
      this.resetForm('initEnterpriseForm')
    },
    // 树形菜单加载
    getMenuTreeData() {
      selectTreeMenu().then(resp => {
        if (resp) {
          this.menuOptions = resp.data
        }
      })
    },
    // 菜单树禁用
    disabledFn(data) {
      if (data !== null) {
        // 根据自己的节点数据条件设置判断，我只提供了个参考
        return true
      } else {
        return false
      }
    },
    // 部门编码改变时改变部门编码长度字段
    changRuleLength(val) {
      if (val != null && val !== '') {
        this.initEnterprise.ruleLength = val.length + 1
      }
    },

    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getHalfCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 弹框取消按钮
    cancel() {
      this.initVisible = false
      this.$refs.menu.setCheckedKeys([])
      this.empetyInitEnterprise()
      this.$parent.idShowPage = true
      this.$parent.addOrUpdateVisible = false
      this.btnDisabled = false
    },
    // 确定
    submitForm() {
      this.$refs.initEnterpriseForm.validate(validate => {
        // 添加
        if (validate) {
          this.btnDisabled = true
          // let newRuleValue = ''
          // newRuleValue = this.initEnterprise.ruleValue
          this.initEnterprise.ruleValue = parseInt('1' + this.initEnterprise.ruleValue + '')
          initAdd(this.initEnterprise).then(resp => {
            if (resp) {
              this.initVisible = false
              this.$refs.menu.setCheckedKeys([])
              this.$parent.idShowPage = true
              this.$parent.addOrUpdateVisible = false
              this.empetyInitEnterprise()
              this.msgSuccess('初始化成功')
              this.$emit('childrenGetList')
            }
            this.btnDisabled = false
          }).catch(() => {
            this.btnDisabled = false
            this.initEnterprise.ruleValue = ''
          })
        }
      })
    },
    // 获取套餐
    templateDataList() {
      listSysCompanyTemp().then(resp => {
        if (resp) {
          this.templateOptiom = resp.data.rows
        }
      })
    },
    // 套餐类型改变触发的事件
    selectTrigger(id) {
      this.$refs.menu.setCheckedKeys([])
      this.selectMenuIdsbyId(id)
    },
    // 根据企业套餐id查询菜单树menuIds[]
    selectMenuIdsbyId(id) {
      selectSysCompanyTempMenuIdsById(id).then(resp => {
        if (resp) {
          const menuIds = resp.data
          this.$refs.menu.setCheckedKeys(menuIds)
        }
      })
    }
  }
}
</script>
<style scoped>
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
    height:30px; line-height:30px;
    text-align: left;
    padding-left: 10px;
    font-size: 14px;
    font-weight:bolder;
    margin-bottom: 20px;
  }
  .bg-purple {
    background: #FFEEDD;
    color:#0a2140;
  }
  .dialog-footer{
    text-align: center;
    display: block;
    padding-bottom:50px;
  }
</style>
